package com.icesoft.base.manager.controller.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.icesoft.base.manager.config.CopyrightProperty;
import com.icesoft.base.manager.security.config.LoginPropertySetting;
import com.icesoft.base.manager.security.config.SecurityConst;
import com.icesoft.core.Const;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.web.suppose.safehttp.SafeRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 系统登录公开参数接口
 */
@RestController
@RequestMapping("public/")
@Slf4j
@AllArgsConstructor
public class ManagerCommonPublicController {
    private final LoginPropertySetting loginPropertySetting;
    private final CopyrightProperty copyrightProperty;
    private static final String BASE_STRING = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ23456789";

    /**
     * 验证码接口
     */
    @GetMapping("captcha")
    public void captcha(@RequestParam(required = false, defaultValue = "120") int width, HttpServletRequest request,
                        @RequestParam(required = false, defaultValue = "40") int height, HttpServletResponse response) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(width, height, 4, 10);
        captcha.setGenerator(new RandomGenerator(BASE_STRING, 4));
        WebUtils.setSessionAttribute(request, SecurityConst.SESSION_CAPTCHA, captcha.getCode());
        captcha.write(response.getOutputStream());
    }

    /**
     * 获取登录配置
     */
    @GetMapping("system/loginSetting")
    public Resp loginSetting() {
        Map<String, Object> map = new HashMap<>();
        map.put("copyrightSetting", copyrightProperty.toMap());
        map.put("loginSetting", loginPropertySetting.getLoginSetting());
        return Resp.success(map);
    }

    /**
     * 加密接口测试接口
     */
    @SafeRequest
    @PostMapping("test/testAppRequest")
    public Resp<?> testAppRequest(HttpServletRequest request) {
        return Resp.success(request.getAttribute(Const.REQUEST_RESOLVER_PARAM_MAP_NAME), "请求成功");
    }
}